package com.lagou.edu.utils;

import com.alibaba.druid.pool.DruidDataSource;
import org.I0Itec.zkclient.ZkClient;

public class DruidUtils {

    private DruidUtils() {
    }

    private static DruidDataSource druidDataSource = new DruidDataSource();
    //连接zookeeper
    private static ZkClient zkClient = new ZkClient("101.133.232.19:2181");


    static {
        //使用自定义序列化
        zkClient.setZkSerializer(new MySerializer());

        //刷新数据库连接池
        refreshDataSource();
    }

    private static void refreshDataSource() {
        //获取数据库连接信息
        String driverClass = zkClient.readData("/aliyun-mysql/driverClass").toString();
        String url = zkClient.readData("/aliyun-mysql/url").toString();
        String username = zkClient.readData("/aliyun-mysql/username").toString();
        String password = zkClient.readData("/aliyun-mysql/password").toString();

        //设置数据库连接池
        druidDataSource.setDriverClassName(driverClass);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
    }

    public static DruidDataSource getInstance() {
        //刷新数据库连接池
        refreshDataSource();
        return druidDataSource;
    }
}
